﻿using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

namespace PlurkApi
{
    public class karma_status
    {
        #region Properties

        /// <summary>
        ///   Returns a list of 30 recent karma updates.
        /// </summary>
        public karma_trends karma_trends { get; set; }

        /// <summary>
        ///   This value is a string and can be: friends_rejections, inactivity, too_short_responses
        /// </summary>
        public string karma_fall_reason { get; set; }

        /// <summary>
        ///   current karma value
        /// </summary>
        public double current_karma { get; set; }

        /// <summary>
        ///   the karma graph url (google chart)
        /// </summary>
        public string karma_graph { get; set; }

        #endregion

        public karma_status()
        {
            karma_trends = new karma_trends();

            karma_fall_reason = string.Empty;            
            current_karma = 0.0;
            karma_graph = string.Empty;
        }

        public karma_status(string jsonString)
        {
            var obj = JObject.Parse(jsonString);
            if (obj.Count <= 0) { return; }

            karma_fall_reason = (obj["karma_fall_reason"] == null) ? string.Empty : (string)obj["karma_fall_reason"];
            current_karma = (obj["current_karma"] == null) ? 0.0 : (double)obj["current_karma"];
            karma_graph = (obj["karma_graph"] == null) ? string.Empty : (string)obj["karma_graph"];

            karma_trends = new karma_trends();
            if (obj["karma_trend"] != null)
            {
                var trendObjs = JArray.Parse(obj["karma_trend"].ToString());
                foreach (var trendObj in trendObjs)
                {
                    karma_trends.Add(new karma_trend((string)trendObj));
                }
            }
        }
    }

    public class karma_trend
    {
        #region Properties

        /// <summary>
        ///   current_time.
        /// </summary>
        public DateTime? current_time { get; set; }

        /// <summary>
        ///   karma__value.
        /// </summary>
        public double? karma_value { get; set; }

        #endregion

        public karma_trend(string jsonString)
        {
            var args = jsonString.Split('-');
            if (args.Length != 2)
            {
                current_time = null;
                karma_value = null;
            }
            else
            {
                var orgin = new DateTime(1970, 1, 1, 0, 0, 0);
                current_time = orgin.AddSeconds(double.Parse(args[0]));
                karma_value = double.Parse(args[1]);
            }
        }
    }

    public class karma_trends : List<karma_trend>
    {
    }
}